<template>
	<view class="header" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
		<view class="user-info">
			<view class="avatar-box">
				<view class="large">
					<image class="avatar-img" :src="user.avatar" @error="imageError">
					</image>
				</view>
				<!-- 修改头像上传按钮，使用微信小程序的chooseAvatar API -->
				<button class="upload-sign" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" v-if="!uploading">
					<view>+</view>
				</button>
				<!-- 上传中状态 -->
				<view v-if="uploading" class="upload-sign uploading">
					<view class="loading-icon">⟳</view>
				</view>
			</view>
			<view class="flex-center">
				<view v-if="user && Object.keys(user).length > 0">
					<view class="name-row">
						<text class="username">{{ user.nickName }}</text>
					</view>
				</view>
				<view v-else class="login-prompt" @click="handleLogin">
					<view class="login-text">
						立即登录
					</view>
				</view>
			</view>
		</view>
		<view class="signature">{{ userAdditionalInfo.bio || '暂无个性签名' }}</view>
		<view class="sign">
			<view class="flex-center">
				<view class="gender-badge">
					<view class="gender-b" v-if="user.sex === '0'">男</view>
					<view class="gender-g" v-else>女</view>
				</view>
			</view>
		</view>
		<!-- 数据面板 -->
		<view class="data-panel">
			<view class="user-data">
				<view v-for="(item, index) in panelData" :key="item.label" @click="handleDataClick(item, index)">
					<view class="user-number">{{ item.value }}</view>
					<view class="user-label">{{ item.label }}</view>
				</view>
			</view>
			<view class="edit-btns">
				<view class="btn" @click="handleEditProfile">编辑资料</view>
				<view class="btn settings-btn" @click="handleSettings">
					<text class="settings-icon">⚙️</text>
				</view>
			</view>
		</view>
		<scroll-view class="other-panel-scroll" scroll-x="true" show-scrollbar="false" enhanced="true"
			:scroll-with-animation="true">
			<view class="other-panel">
				<view class="other-box" v-for="item in panelOtherData" :key="item.title"
					@click="handleOtherClick(item)">
					<view class="other-title">{{ item.title }}</view>
					<view class="other-label">{{ item.label }}</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { ref, defineProps, defineEmits, computed, onMounted } from 'vue'
	import useUserStore from '@/store/modules/user'
	import { uploadFile } from '@/api/upload/upload'
	import { updateUserProfile } from '@/api/system/user' 

	// 获取屏幕边界到安全区域距离
	const { safeAreaInsets } = uni.getWindowInfo()
	const userStore = useUserStore()
	const user = computed(() => userStore.user)
	const userAdditionalInfo = computed(() => userStore.userAdditionalInfo)

	// 添加上传状态
	const uploading = ref(false)

	// 组件挂载时获取用户信息
	onMounted(async () => {
		if (userStore.token && (!user.value || Object.keys(user.value).length === 0)) {
			try {
				await userStore.getInfo()
			} catch (error) {
				console.error('获取用户信息失败:', error)
			}
		}
	})

	interface PanelDataItem {
		value : number | string
		label : string
	}

	interface PanelOtherDataItem {
		title : string
		label : string
	}

	// Props定义
	interface Props {
		panelData ?: PanelDataItem[]
		panelOtherData ?: PanelOtherDataItem[]
	}

	const props = withDefaults(defineProps<Props>(), {
		panelData: () => [],
		panelOtherData: () => []
	})

	// 事件定义
	const emit = defineEmits<{
		editProfile : [],
		otherClick : [item: PanelOtherDataItem],
		imageError : [],
		login : [], // 新增登录事件
		settings : []
	}>()

	// 修改头像上传方法，使用updateUserProfile更新用户信息
	const onChooseAvatar = async (e : any) => {
		const { avatarUrl } = e.detail
		if (!avatarUrl) {
			uni.showToast({
				title: '请选择头像',
				icon: 'none'
			})
			return
		}

		uploading.value = true

		try {
			// 使用upload.ts的uploadFile方法上传头像
			const response = await uploadFile(avatarUrl, 'minio', 'MASTER')

			if (response.code === 200 && response.url) {
				// 更新用户头像信息到后端，使用updateUserProfile
				const updatedUser = { ...user.value, avatar: response.url }
				await updateUserProfile(updatedUser)

				// 更新本地用户信息
				await userStore.getInfo()

				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				})
			} else {
				uni.showToast({
					title: '头像上传失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('头像上传失败:', error)
			uni.showToast({
				title: '头像上传失败',
				icon: 'none'
			})
		} finally {
			uploading.value = false
		}
	}

	const handleEditProfile = () : void => {
		emit('editProfile')
	}

	const handleOtherClick = (item : PanelOtherDataItem) : void => {
		emit('otherClick', item)
	}

	const imageError = () : void => {
		emit('imageError')
		console.log('图片加载失败')
	}

	// 新增登录方法
	const handleLogin = () : void => {
		emit('login')
		// 或者直接跳转到登录页面
		uni.reLaunch({
			url: '/pages/register/wxRegister'
		});
	}

	// 新增设置方法
	const handleSettings = () : void => {
		emit('settings')
		// 或者直接跳转到设置页面
		uni.navigateTo({
			url: '/pages/mine/setting' // 根据你的设置页面路径调整
		});
	}

	// 新增数据面板点击方法
	const handleDataClick = (item: PanelDataItem, index: number) => {
		if (item.label === '关注' || item.label === '粉丝') {
			const activeTab = item.label === '关注' ? 'following' : 'fans'
			uni.navigateTo({
				url: `/pages/mine/followAndFans?userId=${user.value.userId}&activeTab=${activeTab}`
			})
		}
	}
</script>

<style lang="scss" scoped>
	.gradient {
		&-circle {
			border-radius: 50%;
			background: white;

			&.large {
				width: 130rpx;
				height: 130rpx;
				border: 4rpx solid #fff;
				box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
			}
		}
	}

	.flex-center {
		display: flex;
		justify-content: center;
		align-items: center;

		.login-prompt {
			cursor: pointer;
			transition: all 0.3s ease;

			&:hover {
				transform: scale(1.05);
			}

			.login-text {
				color: #fff;
				font-size: 32rpx;
				font-weight: 600;
				padding: 16rpx 32rpx;
				border: 2rpx solid #fff;
				border-radius: 40rpx;
				background: rgba(250, 233, 62, 0.1);
				text-align: center;
				backdrop-filter: blur(10rpx);
				box-shadow: 0 4rpx 12rpx rgba(250, 233, 62, 0.3);

				&:active {
					background: rgba(250, 233, 62, 0.2);
					transform: scale(0.98);
				}
			}
		}
	}

	.header {
		background: linear-gradient(180deg, #1C2D41 0%, #546366 100%);
		padding: 100rpx 30rpx 80rpx 30rpx;

		.user-info {
			display: flex;
			margin-top: 50rpx;

			.avatar-box {
				position: relative;
				margin-right: 32rpx;

				.avatar-img {
					width: 130rpx;
					height: 130rpx;
					border-radius: 50%;
				}

				.upload-sign {
					font-size: 36rpx;
					line-height: 20rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: #FAE93E;
					position: absolute;
					font-weight: 600;
					right: 12rpx;
					bottom: 6rpx;
					border-radius: 50%;
					width: 40rpx;
					height: 40rpx;
					cursor: pointer;
				}
			}
		}

		.name-row {
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;

			.username {
				color: #EFFAFB;
				font-size: 30rpx;
				font-weight: 700;
				margin-right: 16rpx;
			}
		}

		.signature {
			color: #BCC1C4;
			font-size: 28rpx;
			padding-top: 34rpx;
		}

		.sign {
			display: flex;
			padding-top: 20rpx;

			.flex-center {
				display: flex;
				align-items: center;
				gap: 16rpx; // 添加间距
			}

			.gender-badge {
				display: flex;
				text-align: center;
				align-items: center;
				justify-content: center;
				background-color: #707F84;
				width: 50rpx;
				height: 50rpx;
				padding: 4rpx 12rpx;
				font-size: 26rpx;
				border-radius: 40rpx;
				text-align: center;
				line-height: 46rpx;

				.gender-b {
					color: #0000ff;
				}

				.gender-g {
					color: #FF8597;
				}
			}
		}
	}

	.data-panel {
		display: flex;
		justify-content: space-between;
		font-size: 26rpx;
		padding: 50rpx 0;
		color: #BCC1C4;

		.user-data {
			display: flex;
			justify-content: space-between;
			gap: 50rpx;

			> view {
				cursor: pointer;
				transition: all 0.3s ease;
				border-radius: 12rpx;
				padding: 8rpx;

				&:active {
					background: rgba(255, 255, 255, 0.1);
					transform: scale(0.95);
				}
			}

			.user-number {
				color: #EFFAFB;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.user-label {
				font-size: 22rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.edit-btns {
			display: flex;
			gap: 16rpx; // 添加按钮间距

			.btn {
				padding: 0 32rpx;
				border-radius: 40rpx;
				color: #EFFAFB;
				border: 1rpx solid rgba(248, 251, 251, 0.296);
				background-color: #637376;
				display: flex;
				align-items: center;
				cursor: pointer;

				&.settings-btn {
					padding: 0rpx; // 设置按钮稍微小一点
					min-width: 60rpx;
					justify-content: center;

					.settings-icon {
						font-size: 28rpx;
					}
				}
			}
		}
	}

	.other-panel-scroll {
		width: 100%;
		white-space: nowrap;
	}

	.other-panel {
		font-size: 24rpx;
		color: #BCC1C4;
		display: flex;
		gap: 20rpx;
		// 新增以下样式使其可以横向滚动
		width: max-content; // 让容器宽度适应内容
		min-width: 100%; // 确保至少占满父容器宽度

		.other-box {
			background-color: #637376;
			padding: 20rpx;
			border-radius: 16rpx;
			width: 200rpx;
			cursor: pointer;
			flex-shrink: 0; // 防止盒子被压缩

			.other-label {
				font-size: 20rpx;
			}

			.other-title {
				color: #EFFAFB;
				padding-bottom: 6rpx;
			}
		}
	}
</style>
